<template>
  <div class="tmpl">
    <div class="bg"></div>
    <div class="bg-layout"></div>
    <div class="container-center">
      <div class="panel">
        <div class="bg"></div>
        <div class="bg-layout"></div>
        <div class="login-form">
          <h1>LOGIN</h1>
          <el-form :model="loginForm" ref="loginForm" :rules="loginRules" status-icon>
            <el-form-item label="Username:" prop="username" class="el-label">
              <el-input v-model="loginForm.username" placeholder="Input Your Username" autocomplete="on"></el-input>
            </el-form-item>
            <el-form-item label="Password:" prop="password" class="el-label">
              <el-input type="password" v-model="loginForm.password" placeholder="Input Your Password" show-password @keyup.enter.native="handleLogin('loginForm')"></el-input>
            </el-form-item>
            <el-button :icon="captchaIcon" :class="captchaClass" :loading="isLoading" @click="showCaptcha">{{captchaText}}</el-button>
            <el-form-item>
              <el-button type="primary" @click="handleLogin('loginForm')">LOGIN</el-button>
            </el-form-item>
          </el-form>
          <el-dialog title="请拖动滑块完成拼图" width="360px" :visible.sync="isShowSliderVerify" :close-on-click-modal="false" @closed="refresh" append-to-body>
            <slider-verify ref="sliderVerify" @success="onSuccess" @fail="onFail" @again="onAgain"/>
          </el-dialog>
          <hr>
          <div class="login-footer">
            <p>系统管理员账号</p>
            <p>admin / 123</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Index from '@/components/Index/Index'
import sliderVerify from '@/components/Login/SliderVerify'
export default {
  name: 'Login',
  components: {
    Index, sliderVerify
  },
  data () {
    var checkIsNull = (rule, value, callback) => {
      setTimeout(() => {
        if (!value) {
          return callback(new Error('Field Required'))
        } else {
          callback()
        }
      }, 500)
    }
    return {
      bgurl: require('../../assets/img/background/login-bg.jpg'),
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ validator: checkIsNull, trigger: 'blur' }],
        password: [{ validator: checkIsNull, trigger: 'blur' }]
      },
      // 验证码图片
      captchaSrc: '',
      // 登录状态
      isLoading: false,
      // 是否显示滑块验证
      isShowSliderVerify: false,
      isSliderPass: false,
      captchaText: '点此按钮开始验证',
      captchaIcon: 'el-icon-remove',
      captchaClass: 'captcha-undo'
    }
  },
  mounted: function () {
    // 默认用户名密码
    this.loginForm.username = 'admin'
    this.loginForm.password = '123'
  },
  methods: {
    handleLogin (formName) {
      this.$refs[formName].validate((valid) => {
        // 判断校验规则是否满足
        if (valid) {
          // 判断验证码是否校验通过
          if (!this.isSliderPass) {
            this.$notify({
              type: 'warning',
              title: '警告',
              message: '请点击完成验证'
            })
            return
          }

          let username = this.loginForm.username
          let password = this.loginForm.password
          this.$apis.login({username: username, password: password, type: 'COMMON'}).then(res => {
            console.log(res)
            if (res && res.code === '200') {
              this.$notify({
                title: '成功',
                message: '登陆成功，欢迎你 ' + username,
                type: 'success'
              })
              localStorage.setItem('access-token', res.result['accessToken'])
              localStorage.setItem('refresh-token', res.result['refreshToken'])
              localStorage.setItem('user', JSON.stringify(res.result))
              this.$router.push({ path: '/Index' })
            } else {
              console.log(res)
              let errorMsg = res.message ? res.message : '登陆失败'
              this.$notify.error({
                title: '错误',
                message: errorMsg
              })
              // 重置验证码
              this.resetCaptcha()
            }
          }).catch(err => {
            console.log(err)
            this.$message.error('登陆失败')
            // 重置验证码
            this.resetCaptcha()
          })
        }
      })
    },
    showCaptcha () {
      if (this.isSliderPass) {
        return
      }
      this.isShowSliderVerify = true
    },
    /* 滑动验证成功 */
    onSuccess (captcha) {
      console.log(captcha)
      // 请求后端校验验证码
      this.isSliderPass = false
      this.$apis.checkCaptcha(captcha).then(res => {
        if (res && res.code === '200') {
          this.$refs.sliderVerify.verifySuccessEvent()
          this.isSliderPass = true
          this.captchaText = '验证通过'
          this.captchaIcon = 'el-icon-circle-check'
          this.captchaClass = 'captcha-pass'
          setTimeout(() => {
            this.isShowSliderVerify = false
          }, 500)
          this.$notify({
            title: '成功',
            message: '验证通过',
            type: 'success'
          })
        } else {
          this.$refs.sliderVerify.verifyFailEvent(res.message)
        }
        this.isLoading = false
      }).catch(err => {
        console.log(err)
        this.isLoading = false
        this.$notify.error({
          title: '错误',
          message: '请求异常'
        })
      })
    },
    /* 滑动验证失败 */
    onFail (msg) {
      console.log(111)
      console.log(msg)
      this.$notify.error({
        title: '错误',
        message: msg || '验证失败，请控制拼图对齐缺口'
      })
    },
    /* 滑动验证异常 */
    onAgain () {
      this.$notify.error({
        title: '错误',
        message: '滑动操作异常，请重试'
      })
    },
    /* 刷新验证码 */
    refresh () {
      this.$refs.sliderVerify.refresh()
    },
    /* 提示弹框 */
    message (type, message) {
      this.$message({
        showClose: true,
        type: type,
        message: message,
        duration: 1500
      })
    },
    /* 登陆失败后重置验证码 */
    resetCaptcha () {
      this.isShowSliderVerify = false
      this.isSliderPass = false
      this.captchaText = '点此按钮开始验证'
      this.captchaIcon = 'el-icon-remove'
      this.captchaClass = 'captcha-undo'
    }
  }
}
</script>

<style scoped>
  .tmpl {
    height: 100%;
  }
  .tmpl > .bg, .tmpl > .bg-layout {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
  }
  .tmpl > .bg-layout {
    background-color: rgba(34, 31, 31, .6);
  }
  .tmpl > .bg {
    background-color: #000;
    background-image: url(../../assets/img/background/login-bg.jpg);
    background-size: cover;
    filter: blur(3px);
  }
  .container-center {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
  .panel {
    width: 360px;
    height: 500px;
    border: 1px solid #1A1717;
    border-radius: 10px;
    position: relative;
    overflow: hidden;
    box-shadow: 0 0 10px #000;
  }
  .panel .bg, .panel .bg-layout {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
  .panel > .bg {
    background-image: url(../../assets/img/background/login-bg.jpg);
    background-size: cover;
    background-position: 50%;
  }
  .panel .bg-layout {
    background: radial-gradient(circle at top, #1A1717, #000);
    background-image: -webkit-radial-gradient(top center, #1A1717, #000);
    opacity: 0.7;
  }
  .panel .login-form {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #fff;
    text-align: center;
    padding: 0 20px;
  }
  .el-form-item >>> label {
    font-size: 15px;
    color: #fff;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
  .el-button {
    width: 100%;
    margin: 10px 0;
    font-size: 17px;
  }
  .panel hr {
    border: 0;
    border-bottom: 1px solid rgba(255, 255, 255, .3);
  }
  .el-input >>> input {
    background-color: transparent;
    color: rgba(255, 255, 255, .8);
  }
  .captcha-pass {
    width: 100%;
    padding: 6px 20px;
    font-size: 17px;
    color: #fff;
    border-color: #6bc5a4;
    background: #6bc5a4;
    line-height: 30px;
  }
  .captcha-undo {
    width: 100%;
    padding: 6px 20px;
    font-size: 17px;
    color: #fff;
    border-color: #fff;
    background: transparent;
    line-height: 30px;
  }
</style>
